package org.jeecgframework.web.controller;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.mail.internet.MimeUtility;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.log4j.Logger;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.common.model.json.ValidForm;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.ExceptionUtil;
import org.jeecgframework.core.util.FileUtils;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.TemplateExportParams;
import org.jeecgframework.poi.excel.entity.vo.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.vo.TemplateExcelConstants;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.service.CbsQuotationServiceI;
import org.jeecgframework.web.service.ZyPlanRecordServiceI;
import org.jeecgframework.web.service.ZyWorkFlowService;
import org.jeecgframework.web.system.pojo.base.CbsProcurementNoteEntity;
import org.jeecgframework.web.system.pojo.base.CbsQuotationDetailEntity;
import org.jeecgframework.web.system.pojo.base.CbsQuotationEntity;
import org.jeecgframework.web.system.pojo.base.TSRoleUser;
import org.jeecgframework.web.system.pojo.base.TSUser;
import org.jeecgframework.web.system.pojo.base.TSUserOrg;
import org.jeecgframework.web.system.pojo.base.ZyPlanRecordEntity;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.web.util.FileBean;
import org.jeecgframework.web.util.SendMailUtil;
import org.jeecgframework.web.util.StaticValue;
import org.jeecgframework.web.util.UploadFileUtil;
import org.jeecgframework.workflow.common.WorkFlowGlobals;
import org.jeecgframework.workflow.service.ActivitiService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;



/**
 * @Title: Controller
 * @Description: 报价单表
 * @author onlineGenerator
 * @date 2016-08-03 15:37:22
 * @version V1.0
 *
 */
@Scope("prototype")
@Controller
@RequestMapping("/cbsQuotationController")
public class CbsQuotationController extends BaseController {
    /**
     * Logger for this class
     */
    private static final Logger logger = Logger.getLogger(CbsQuotationController.class);

    @Autowired
    private CbsQuotationServiceI cbsQuotationService;
    @Autowired
    private SystemService systemService;
    @Autowired
    private ZyWorkFlowService zyWorkFlowService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private ActivitiService activitiService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private ZyPlanRecordServiceI zyPlanRecordService;
    private String message;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }


    /**
     * 报价单表列表 页面跳转
     *
     * @return
     */
    @RequestMapping(params = "cbsQuotation")
    public ModelAndView cbsQuotation(HttpServletRequest request) {
        return new ModelAndView("com/buss/quotation/cbsQuotationList");
    }



    /**
     * 报价单审批页面跳转
     *
     * @return
     */
    @RequestMapping(params = "goApproval")
    public ModelAndView goApproval(HttpServletRequest request,String taskId,String instId,String busId,String isDetail){
        CbsQuotationEntity quotation = systemService.get(CbsQuotationEntity.class, busId);
        request.setAttribute("bus", quotation.getNote());
        request.setAttribute("instId", instId);
        request.setAttribute("quotation", quotation);
        request.setAttribute("isDetail", isDetail);
        List<ZyPlanRecordEntity> recordList = systemService.findHql("from ZyPlanRecordEntity where busId = ? order by createDate desc", quotation.getNote().getId());
        request.setAttribute("recordList", recordList);
        if("2".equals(isDetail)){
            request.setAttribute("canDown","1");
            return new ModelAndView("com/zybk/cbs_curement_note/cbsProcurementNote-approval");
        }else if("3".equals(isDetail)){
            if("2".equals(quotation.getType())){
                TSUser user = ResourceUtil.getSessionUserName();
                List<TSRoleUser> userOrgList = systemService.findHql("from TSRoleUser where TSUser.id = ?", user.getId());
                for (TSRoleUser roleUser : userOrgList) {
                    if(StaticValue.RULE_CODE_BARCO_CSA.equals(roleUser.getTSRole().getRoleCode())){
                        request.setAttribute("btnFlag", "0");
                    }
                }
            }else{
                request.setAttribute("btnFlag", "0");
            }
            request.setAttribute("isDetail", 2);
            List<ProcessInstance> insts = runtimeService.createProcessInstanceQuery().processInstanceBusinessKey(busId).active().list();
            if(insts.size() > 0){
                request.setAttribute("canDown",0);
            }
            return new ModelAndView("com/zybk/cbs_quotation/cbsQuotation-send");
        }
        Task task = activitiService.getTask(taskId);
        request.setAttribute("task", task);
        if(!StringUtil.isNotEmpty(task) || "taskNode0".equals(task.getTaskDefinitionKey())){
            return new ModelAndView("com/zybk/cbs_quotation/cbsQuotation-edit");
        }else if("taskNode1".equals(task.getTaskDefinitionKey()) || "taskNode2".equals(task.getTaskDefinitionKey())){
            /*List<ProcessInstance> insts = runtimeService.createProcessInstanceQuery().processInstanceBusinessKey(busId).active().list();
            if(insts.size() > 0){
                request.setAttribute("canDown",1);
            }*/
            request.setAttribute("canDown",1);
            return new ModelAndView("com/zybk/cbs_quotation/cbsQuotation-send");
        }
        return null;
    }

    /**
     * easyui AJAX请求数据
     *
     * @param request
     * @param response
     * @param dataGrid
     */

    @RequestMapping(params = "datagrid")
    public void datagrid(CbsQuotationEntity cbsQuotation,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        CriteriaQuery cq = new CriteriaQuery(CbsQuotationEntity.class, dataGrid);
        //查询条件组装器
        org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, cbsQuotation, request.getParameterMap());
        try{
            //自定义追加查询条件
        }catch (Exception e) {
            throw new BusinessException(e.getMessage());
        }
        cq.add();
        this.cbsQuotationService.getDataGridReturn(cq, true);
        TagUtil.datagrid(response, dataGrid);
    }

    /**
     * 报价单表新增页面跳转
     *
     * @return
     */
    @RequestMapping(params = "goAdd")
    public ModelAndView goAdd(CbsQuotationEntity cbsQuotation, HttpServletRequest req) {
        if (StringUtil.isNotEmpty(cbsQuotation.getId())) {
            cbsQuotation = cbsQuotationService.getEntity(CbsQuotationEntity.class, cbsQuotation.getId());
            req.setAttribute("cbsQuotationPage", cbsQuotation);
        }
        return new ModelAndView("com/buss/quotation/cbsQuotation-add");
    }



    /**
     * 确认发送报价单 - 跳转
     *
     * @return
     */
    @RequestMapping(params = "goQuotationSend")
    public ModelAndView goQuotationSend(HttpServletRequest req,String taskId,String instId,String quotationId) {
        CbsQuotationEntity quotation = systemService.get(CbsQuotationEntity.class, quotationId);
        req.setAttribute("bus", quotation.getNote());
        req.setAttribute("quotation", quotation);
        Task task = activitiService.getTask(taskId);
        req.setAttribute("task", task);
        req.setAttribute("instId", instId);
        List<ZyPlanRecordEntity> recordList = systemService.findHql("from ZyPlanRecordEntity where busId = ? order by createDate desc", quotation.getNote().getId());
        req.setAttribute("recordList", recordList);
        if("2".equals(quotation.getType())){
            TSUser user = ResourceUtil.getSessionUserName();
            List<TSRoleUser> userOrgList = systemService.findHql("from TSRoleUser where TSUser.id = ?", user.getId());
            for (TSRoleUser roleUser : userOrgList) {
                if(StaticValue.RULE_CODE_BARCO_CSA.equals(roleUser.getTSRole().getRoleCode())){
                    req.setAttribute("btnFlag", "3");
                }
            }
        }else{
            req.setAttribute("btnFlag", "3");
        }
        return new ModelAndView("com/zybk/cbs_quotation/cbsQuotation-send");
    }





    /**
     * 添加报价单表
     *
     * @return
     */
    @RequestMapping(params = "doAdd")
    @ResponseBody
    public AjaxJson doAdd(HttpServletRequest request,String noteId,String taskId,String instId,String state) {
        AjaxJson j = new AjaxJson();
        message = "报价单创建成功";
        j.setObj(state);
        try{
            CbsProcurementNoteEntity note = systemService.get(CbsProcurementNoteEntity.class, noteId);
            CbsQuotationEntity quotation = cbsQuotationService.createQuotation(note,"0");
            TSUser user = ResourceUtil.getSessionUserName();
            //签收
            taskService.claim(taskId, user.getUserName());
            zyWorkFlowService.processComplete("2", instId, user.getUserName(),state , "flag");
            Map<String, Object> map = new HashMap<String, Object>();
            if(!"0".equals(state)){
                Task task = taskService.createTaskQuery().processInstanceId(instId).active().singleResult();
                taskService.claim(task.getId(), user.getUserName());
                map.put("taskId", task.getId());
                zyPlanRecordService.savePlanRecord(note.getId(), instId, task.getId(), "", user.getUserName(), message);
            }
            map.put("instId", instId);
            map.put("busId", noteId);
            j.setObj(map);
            systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
        }catch(Exception e){
            e.printStackTrace();
            message = "报价单创建失败";
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 报价单表编辑页面跳转
     *
     * @return
     */
    @RequestMapping(params = "goUpdate")
    public ModelAndView goUpdate(CbsQuotationEntity cbsQuotation, HttpServletRequest req) {
        if (StringUtil.isNotEmpty(cbsQuotation.getId())) {
            cbsQuotation = cbsQuotationService.getEntity(CbsQuotationEntity.class, cbsQuotation.getId());
            req.setAttribute("cbsQuotationPage", cbsQuotation);
        }
        return new ModelAndView("com/buss/quotation/cbsQuotation-update");
    }

    /**
     * 更新报价单表
     * @param request
     * @param quotationId 报价单id
     * @param detailId	修改的报价单详细的id
     * @param disCount	折扣率
     * @param disCountPrice 折扣价
     * @param num 数量
     * @param total 小计
     * @return
     */
    @RequestMapping(params = "doUpdate")
    @ResponseBody
    public AjaxJson doUpdate( HttpServletRequest request,String quotationId,String detailId,String instId,String taskId,
                              String disCount,String disCountPrice,String lastPrice,String num,String total,String manpowerNumber,String travelNumber,String state,String isOnsiteServices) {
        AjaxJson j = new AjaxJson();
        CbsQuotationEntity quotation = cbsQuotationService.get(CbsQuotationEntity.class, quotationId);
        message = "2".equals(quotation.getType())?"报价单提交审批成功":"报价单提交成功";
        try {
            DecimalFormat df = new DecimalFormat("#.00");
            TSUser user = ResourceUtil.getSessionUserName();
            String detailIds [] = detailId.split(",");
            String disCountPrices [] = disCountPrice.split(",");
            String nums [] = num.split(",");
            String totals [] = total.split(",");
            String lastPrices [] = lastPrice.split(",");
            Double count = 0.00;
            if(quotation.getNote() != null){
                quotation.getNote().setIsOnsiteServices("0".equals(isOnsiteServices)?"0":"1");
            }
            for (CbsQuotationDetailEntity detail : quotation.getQuotationDetailList()) {
                for (int i = 0; i < detailIds.length; i++) {
                    if(detail.getId().equals(detailIds[i])){
                        detail.setNum(Integer.parseInt(nums[i]));
                        /*设置零件关联表的零件数量*/
                        detail.getProcurementPart().setNum(nums[i]);
                        detail.setDisCountPrice(Integer.parseInt(disCountPrices[i]));
                        detail.setTotal(Integer.parseInt(totals[i]));
                        detail.setLastPrice(Integer.parseInt(lastPrices[i]));
                        count = count + detail.getTotal();
                        systemService.saveOrUpdate(detail);
                    }
                }
            }
            if("1".equals(isOnsiteServices)){
                if(StringUtil.isNotEmpty(manpowerNumber)){
                    quotation.setManpowerNumber(Integer.parseInt(manpowerNumber));
                    if (StringUtil.isNotEmpty(quotation.getManpowerPrice())) {
                        count += quotation.getManpowerNumber() * quotation.getManpowerPrice();
                    } else {
                        count += 0;
                    }
                }
                if(StringUtil.isNotEmpty(travelNumber)){
                    quotation.setTravelNumber(Integer.parseInt(travelNumber));
                    count += quotation.getTravelNumber() * quotation.getTravelPrice();
                }
            }
            quotation.setState("1");
            quotation.setTotal((int)Math.rint(count) + "");
            quotation.setDisCount(Integer.parseInt(disCount));
//			如果是提交
            if(!"4".equals(state)){
                /*设置状态为审批中*/
                quotation.setState("5");
                String outPath = cbsQuotationService.genQuotationExcel(quotation, request);
                outPath = FileUtils.getFilePrefix(outPath) + ".pdf";
                quotation.setPdfUrl(outPath);
                //2 = csa创建
                if("2".equals(quotation.getType())){
                    if(StringUtil.isEmpty(taskId)){
                        quotation.setState(state);
                        ProcessInstance inst = zyWorkFlowService.startOnlineProcess("cbs_quotation", quotation.getId(), new HashMap<String, Object>());
                        Task task = taskService.createTaskQuery().processInstanceId(inst.getProcessInstanceId()).active().singleResult();
                        instId = inst.getProcessInstanceId();
                        taskId = task.getId();
                    }
                    taskService.claim(taskId, user.getUserName());
                    runtimeService.setVariable(instId, WorkFlowGlobals.ASSIGNEE_USER_ID_LIST, user.getUserName());
                    zyWorkFlowService.processComplete("2",instId,"","","");
                    //给服务运营经理发送邮件提醒
                    List<TSRoleUser> roleUserList = systemService.findHql("from TSRoleUser where TSRole.roleCode = ?", StaticValue.RULE_CODE_BARCO_CS_MANAGER);
                    for (TSRoleUser roleUser : roleUserList) {
                        Map<String, Object> rejectMap = new HashMap<String, Object>();
                        String subject = quotation.getNote().getCinema().getName() + "报价单审批";
                        rejectMap.put("quotationNo", quotation.getQuotationNum());
                        rejectMap.put("url",StaticValue.HTTP_HEADER);
                        // TODO 由于给系统用户发送   暂屏蔽掉
                        SendMailUtil.sendHTMLeMail(roleUser.getTSUser().getEmail(), subject, "sms_quotationCSA_approval.ftl", rejectMap,systemService);
                    }
                }
                zyPlanRecordService.savePlanRecord(quotation.getNote().getId(), instId, taskId, "", user.getUserName(), message);
                systemService.saveOrUpdate(quotation);
            }

            systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
        } catch (Exception e) {
            e.printStackTrace();
            message = "报价单更新失败";
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 确认发送mail 提交  并不发邮件，邮件异步请求
     * @param request
     * @param taskId
     * @param instId
     * @param busId
     * @param quotationId
     * @param actionResult
     * @param content
     * @param copyPerson
     * @return
     */
    @RequestMapping(params ="doSendMail")
    @ResponseBody
    public AjaxJson doSendMail(HttpServletRequest request,String taskId,String instId,String busId,String quotationId,String actionResult,String content,String copyPerson){
        AjaxJson json = new AjaxJson();
        message = "报价单发送成功";
        try {
            boolean flag = true;
            TSUser user = ResourceUtil.getSessionUserName();
            CbsQuotationEntity quotation = systemService.get(CbsQuotationEntity.class, quotationId);
            quotation.setCopyPerson(copyPerson);
            if("1".equals(quotation.getType())){
                quotation.setState("2");
                systemService.saveOrUpdate(quotation);
            }else{
                if(StringUtil.isNotEmpty(actionResult)){
                    if("n".equals(zyWorkFlowService.checkTaskHandle(taskId))){
                        message = "发送失败，该任务已被办理";
                        flag = false;
                    }else{
                        taskService.claim(taskId,user.getUserName());
                        zyWorkFlowService.processComplete("2", instId, quotation.getCreateBy(),actionResult , "flag");
                        Task task = taskService.createTaskQuery().processInstanceId(instId).active().singleResult();
                        Object obj = runtimeService.getVariable(instId,WorkFlowGlobals.ASSIGNEE_USER_ID_LIST);
                        taskService.claim(task.getId(), obj.toString());
                        quotation.setState("1");
                        if("0".equals(actionResult)){
                            message = "同意";
                        }else{
                            message = "驳回";
                        }
                        systemService.saveOrUpdate(quotation);
                    }
                }else {
                    quotation.setState("2");
                    systemService.saveOrUpdate(quotation);
                    quotation.getNote().setState("2");
                    systemService.saveOrUpdate(quotation.getNote());
                    zyWorkFlowService.processComplete("2", instId, "","","");
                }
            }
            if(flag){
                zyPlanRecordService.savePlanRecord(quotation.getNote().getId(), instId,taskId, "", user.getUserName(), StringUtil.isNotEmpty(content)?message+"，说明：" + content:message);
            }
            systemService.addLog(message, Globals.log_type_SEND_EMAIL, Globals.Log_Leavel_INFO);
        } catch (Exception e) {
            message = "报价单发送失败";
            json.setSuccess(false);
            e.printStackTrace();
        }
        json.setMsg(message);
        return json;
    }

    /**
     * 实际发送email  异步请求
     * @param quotationId
     */
    @RequestMapping(params="realSendMail")
    @ResponseBody
    public void realSendMail(String quotationId,HttpServletRequest request){
        try {
            CbsQuotationEntity quotation = systemService.get(CbsQuotationEntity.class, quotationId);
            String fileName = quotation.getQuotationNum()+ "-" +quotation.getCreateName()+ "-"+quotation.getNote().getCinema().getName() + "-零件采购报价version1.0.pdf";
            String subject = "中影巴可-"+fileName;
            fileName = MimeUtility.encodeText(fileName);
            String imgMain = StaticValue.HTTP_HEADER+"/plug-in/login/images/mail-img-main.png";
            String imgFooter  = StaticValue.HTTP_HEADER+"/plug-in/login/images/mail-img-footer.jpg";
            String logo  = StaticValue.HTTP_HEADER+"/plug-in/login/images/logo.png";
            Map<String,Object> param = new HashMap<String, Object>();
            param.put("mainCid",imgMain);
            param.put("footerCid",imgFooter);
            param.put("logoCid",logo);
//            SendMailUtil.sendMail(quotation.getNote().getContactMail(), subject, quotation.getPdfUrl(),fileName, quotation.getCopyPerson(), "quotation_send_mail.ftl",param,systemService);
            SendMailUtil.sendMailWithAttach(quotation.getNote().getContactMail(),subject,quotation.getPdfUrl(),fileName,quotation.getCopyPerson(),"quotation_send_mail.ftl",param,systemService);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 判断mail地址是否正确
     * @param param
     * @return
     */
    @RequestMapping(params="validEmail")
    @ResponseBody
    public Map<String, Object> validEmail(String param){
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("status", ValidForm.Y);
        message = "验证通过";
        if(StringUtil.isNotEmpty(param)){
            String mails[] = param.split(",");
            for (String mail : mails) {
                if(!mail.matches("^\\s*\\w+(?:\\.{0,1}[\\w-]+)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\\.[a-zA-Z]+\\s*$")){
                    message = "邮箱格式不正确";
                    map.put("status", ValidForm.N);
                }
            }
        }
        map.put("info", message);
        return map;
    }



    /**
     * 删除报价单表
     *
     * @return
     */
    @RequestMapping(params = "doDel")
    @ResponseBody
    public AjaxJson doDel(CbsQuotationEntity cbsQuotation, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        cbsQuotation = systemService.getEntity(CbsQuotationEntity.class, cbsQuotation.getId());
        message = "报价单表删除成功";
        try{
            cbsQuotationService.delete(cbsQuotation);
            systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
        }catch(Exception e){
            e.printStackTrace();
            message = "报价单表删除失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 批量删除报价单表
     *
     * @return
     */
    @RequestMapping(params = "doBatchDel")
    @ResponseBody
    public AjaxJson doBatchDel(String ids,HttpServletRequest request){
        AjaxJson j = new AjaxJson();
        message = "报价单表删除成功";
        try{
            for(String id:ids.split(",")){
                CbsQuotationEntity cbsQuotation = systemService.getEntity(CbsQuotationEntity.class,
                        id
                );
                cbsQuotationService.delete(cbsQuotation);
                systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
            }
        }catch(Exception e){
            e.printStackTrace();
            message = "报价单表删除失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 导入功能跳转
     *
     * @return
     */
    @RequestMapping(params = "upload")
    public ModelAndView upload(HttpServletRequest req) {
        return new ModelAndView("com/buss/quotation/cbsQuotationUpload");
    }

    /**
     * 导出excel
     *
     * @param request
     * @param response
     */
    @RequestMapping(params = "exportXls")
    public String exportXls(CbsQuotationEntity cbsQuotation,HttpServletRequest request,HttpServletResponse response
            , DataGrid dataGrid,ModelMap modelMap) {
        CriteriaQuery cq = new CriteriaQuery(CbsQuotationEntity.class, dataGrid);
        org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, cbsQuotation, request.getParameterMap());
        List<CbsQuotationEntity> cbsQuotations = this.cbsQuotationService.getListByCriteriaQuery(cq,false);
        modelMap.put(NormalExcelConstants.FILE_NAME,"报价单表");
        modelMap.put(NormalExcelConstants.CLASS,CbsQuotationEntity.class);
        modelMap.put(NormalExcelConstants.PARAMS,new ExportParams("报价单表列表", "导出人:"+ResourceUtil.getSessionUserName().getRealName(),
                "导出信息"));
        modelMap.put(NormalExcelConstants.DATA_LIST,cbsQuotations);
        return NormalExcelConstants.JEECG_EXCEL_VIEW;
    }
    /**
     * 导出excel 使模板
     *
     * @param request
     * @param response
     */
    @RequestMapping(params = "exportXlsByT")
    public String exportXlsByT(CbsQuotationEntity cbsQuotation,HttpServletRequest request,HttpServletResponse response
            , DataGrid dataGrid,ModelMap modelMap) {
        modelMap.put(TemplateExcelConstants.FILE_NAME, "报价单表");
        modelMap.put(TemplateExcelConstants.PARAMS,new TemplateExportParams("Excel模板地址"));
        modelMap.put(TemplateExcelConstants.MAP_DATA,null);
        modelMap.put(TemplateExcelConstants.CLASS,CbsQuotationEntity.class);
        modelMap.put(TemplateExcelConstants.LIST_DATA,null);
        return TemplateExcelConstants.JEECG_TEMPLATE_EXCEL_VIEW;
    }

    /**
     * 下载报价单
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(params="dowQuotaiton")
    public void dowQuotaiton(HttpServletRequest request,HttpServletResponse response,String id){
        CbsQuotationEntity quotation = systemService.get(CbsQuotationEntity.class, id);
        try {
            String fileName = quotation.getQuotationNum()+ "-" +quotation.getCreateName()+ "-"+quotation.getNote().getCinema().getName() + "-零件采购报价version1.0.pdf";
            UploadFileUtil.downFile(request, response, new FileBean(quotation.getPdfUrl(),fileName));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 复制报价单
     * @param request
     * @return
     */
    @RequestMapping(params="copyQuotation")
    public ModelAndView copyQuotation(HttpServletRequest request,String id){
        try {
            CbsQuotationEntity quotation = systemService.get(CbsQuotationEntity.class, id);
            CbsQuotationEntity copyQuotation = new CbsQuotationEntity();
            MyBeanUtils.copyBeanNotNull2Bean(quotation, copyQuotation);
            copyQuotation.setState("4");
            copyQuotation.setId(null);
            copyQuotation.setCreateBy(null);
            copyQuotation.setCreateDate(null);
            copyQuotation.setCreateName(null);
            copyQuotation.setUpdateBy(null);
            copyQuotation.setUpdateDate(null);
            copyQuotation.setUpdateName(null);
            copyQuotation.setQuotationNum(cbsQuotationService.genQuotationNumber(copyQuotation.getNote()));
            if("0".equals(quotation.getType())){
                copyQuotation.setType("1");

            }
            copyQuotation.setQuotationDetailList(null);
            systemService.save(copyQuotation);
            List<CbsQuotationDetailEntity> detailList = new ArrayList<CbsQuotationDetailEntity>();
            for (CbsQuotationDetailEntity detail : quotation.getQuotationDetailList()) {
                CbsQuotationDetailEntity newDetail = new CbsQuotationDetailEntity();
                MyBeanUtils.copyBeanNotNull2Bean(detail, newDetail);
                newDetail.setId(null);
                newDetail.setQuotation(copyQuotation);
                newDetail.setCreateBy(null);
                newDetail.setCreateDate(null);
                newDetail.setCreateName(null);
                newDetail.setUpdateBy(null);
                newDetail.setUpdateDate(null);
                newDetail.setUpdateName(null);
                detailList.add(newDetail);
            }
            systemService.batchSave(detailList);
            CbsQuotationEntity q = systemService.get(CbsQuotationEntity.class, copyQuotation.getId());
            request.setAttribute("quotation", q);
            request.setAttribute("bus", q.getNote());
            TSUser user = ResourceUtil.getSessionUserName();
            message = "报价单复制成功";
            zyPlanRecordService.savePlanRecord(quotation.getNote().getId(), "", "", "", user.getUserName(), message);
            List<ZyPlanRecordEntity> recordList = systemService.findHql("from ZyPlanRecordEntity where busId = ? order by createDate desc", quotation.getNote().getId());
            request.setAttribute("recordList", recordList);
            request.setAttribute("message", message);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ModelAndView("com/zybk/cbs_quotation/cbsQuotation-edit");
    }



    @SuppressWarnings("unchecked")
    @RequestMapping(params = "importExcel", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson importExcel(HttpServletRequest request, HttpServletResponse response) {
        AjaxJson j = new AjaxJson();

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<CbsQuotationEntity> listCbsQuotationEntitys = ExcelImportUtil.importExcelByIs(file.getInputStream(),CbsQuotationEntity.class,params);
                for (CbsQuotationEntity cbsQuotation : listCbsQuotationEntitys) {
                    cbsQuotationService.save(cbsQuotation);
                }
                j.setMsg("文件导入成功！");
            } catch (Exception e) {
                j.setMsg("文件导入失败！");
                logger.error(ExceptionUtil.getExceptionMessage(e));
            }finally{
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return j;
    }
}
